package com.sicnu.cheer.leaugebar.leaguemodle.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;

import com.sicnu.cheer.generalmodule.adapter.base.CommonAdapter;
import com.sicnu.cheer.generalmodule.adapter.viewholder.CommonViewHolder;
import com.sicnu.cheer.generalmodule.bean.EventBean;
import com.sicnu.cheer.generalmodule.bean.LeagueBean;
import com.sicnu.cheer.generalmodule.bean.MyUser;
import com.sicnu.cheer.generalmodule.config.Constant;
import com.sicnu.cheer.generalmodule.util.NetWorkUtil;
import com.sicnu.cheer.generalmodule.util.UIHelper;
import com.sicnu.cheer.generalmodule.fragment.base.BaseFragment;
import com.sicnu.cheer.leaugebar.leaguemodle.R;
import com.sicnu.cheer.xlistview.view.XListView;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;


/**
 * Created by cheer on 2017/1/24.
 * 历史活动布局
 */

public class HisFragment extends BaseFragment {
    private LinearLayout noResultLL;
    private XListView listView;
    private CommonAdapter mAdapter;
    private List<EventBean> eventList;
    private ProgressDialog progressDialog;
    private int pageSize=10;
    private int skip=0;

    @Override
    protected int setLayoutResourceId() {
        return R.layout.layout_list_with_no_data;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    protected void initData(Bundle arguments) {
        super.initData(arguments);
        progressDialog = new ProgressDialog(mActivity);
        progressDialog.setMessage("加载中...");

    }

    public void requestDataFromBmob(final boolean isRefresh) {
        resetState();
        if (!NetWorkUtil.isConnect(mActivity)) {
            UIHelper.ToastMessage(mActivity, "没有网络，请设置网络");
            return;
        }
        if (!progressDialog.isShowing()) {
            progressDialog.show();
        }
        findEvent(isRefresh);

    }

    private void findEvent( final boolean isRefresh) {
        LeagueBean league = MyUser.getCurrentUser(mActivity, MyUser.class).getLeague();

        BmobQuery<EventBean> query = new BmobQuery<EventBean>();
        query.setLimit(pageSize);
        query.setSkip(skip);
        query.addWhereEqualTo("league",league);
        query.include("author,league");
        query.findObjects(mActivity, new FindListener<EventBean>() {
            @Override
            public void onSuccess(List<EventBean> object) {
                stopXListView(isRefresh);
                if (object==null||object.size()==0){
                    setNoResultState(isRefresh);
                }else {
                    if (isRefresh){
                        eventList.clear();
                    }
                    eventList.addAll(object);
                    mAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(int code, String msg) {
                stopXListView(isRefresh);
                UIHelper.ToastMessage(mActivity,"查询失败：" + msg);
            }
        });
    }

    private void stopXListView(boolean isRefresh) {
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        if (isRefresh){
            listView.stopRefresh();
        }else {
            listView.stopLoadMore();
        }
    }
    private void resetState() {
        noResultLL.setVisibility(View.GONE);
        listView.setVisibility(View.VISIBLE);
        listView.setPullLoadEnable(true);
    }

    private void setNoResultState(boolean isRefresh) {
        if (isRefresh){
            noResultLL.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
        }else {
            listView.setPullLoadEnable(false);
            UIHelper.ToastMessage(mActivity, "没有更多数据了");
        }
    }
    @Override
    protected void initView() {
        eventList = new ArrayList<>();
        noResultLL = (findViewById(R.id.no_data_ll));
        noResultLL.setVisibility(View.GONE);
        listView = findViewById(R.id.data_xlv);
        listView.setDividerHeight(0);
        //API21以上才有效果----第二种方式，比较简便
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            listView.setNestedScrollingEnabled(true);
        }
        setXListView();

        //请求服务器上的数据
        requestDataFromBmob(true);

        //将获取到的数据填充界面
        listView.setAdapter(mAdapter = new CommonAdapter<EventBean>(
                mActivity.getApplicationContext(), eventList, R.layout.item_event) {
            @Override
            public void convert(CommonViewHolder helper, EventBean item) {
                if (item!=null) {
                    helper.setImageResource(R.id.event_state_icon_iv, item.getOn() ? R.mipmap.on_going : R.mipmap.finish);
                    helper.setText(R.id.event_title_tv, item.getTitle());
                    helper.setText(R.id.event_content_tv, item.getContent());
                    helper.setText(R.id.event_views_tv, String.valueOf(item.getViews()));
                    try {
                        String likes = String.valueOf(item.getLikesInt());
                        helper.setText(R.id.event_likes_tv,likes );
                    } catch (Exception e) {
                        helper.setText(R.id.event_likes_tv, "0");
                        e.printStackTrace();
                    }
                    helper.setImageByUrl(R.id.event_organizer_iv,item.getLeague().getLogo(),R.mipmap.default_logo);
                }
            }

        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                intent.setClassName(getActivity(), "com.sicnu.cheer.leaugebar.eventmodule.activity.EventDetailActivity");
                intent.putExtra("event", eventList.get(position-1));
                startActivity(intent);
            }
        });

    }

    private void setXListView() {
        listView.setPullLoadEnable(true);
        listView.setPullRefreshEnable(true);
        listView.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                pageSize=10;
                skip=0;
                requestDataFromBmob(true);
            }

            @Override
            public void onLoadMore() {
                pageSize+=10;
                skip+=10;
                requestDataFromBmob(false);
            }
        });
    }

}
